package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.enums.*;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.dto.InvoiceDto;
import com.yunyao.common.dto.InvoiceSourceDto;
import com.yunyao.common.dto.InvoiceSourceOrderDto;
import com.yunyao.common.dto.excel.InvoiceExcelDto;
import com.yunyao.common.dto.excel.SettlementExcelDto;
import com.yunyao.common.dto.order.ProjectOrderDto;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.StringUtils;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.*;
import com.yunyao.dao.service.bamu.*;
import com.yunyao.framework.audit.ProjectOrderAuditHandle;
import com.yunyao.framework.service.InvoiceService;
import com.yunyao.framework.vo.Invoice.*;
import com.yunyao.framework.vo.projectorder.ProjectOrderVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationOrderVO;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class InvoiceServiceImpl implements InvoiceService {
    @Autowired
    private IBamuPurchaseContractService iBamuPurchaseContractService;
    @Autowired
    private IBamuInvoiceApplyService iBamuInvoiceApplyService;
    @Autowired
    private IBamuSupplyApplyService iBamuSupplyApplyService;
    @Autowired
    private ProjectOrderAuditHandle projectOrderAuditHandle;
    @Autowired
    private IBamuInvoiceService iBamuInvoiceService;
    @Autowired
    private IBamuInvoiceSourceOrderService iBamuInvoiceSourceOrderService;
    @Autowired
    private IBamuInvoiceSourceService iBamuInvoiceSourceService;
    @Autowired
    private IBamuPurchaseApplyService iBamuPurchaseApplyService;
    @Autowired
    private IBamuSpReconciliationSettlementService iBamuSpReconciliationSettlementService;
    @Autowired
    private IBamuSpReconciliationService iBamuSpReconciliationService;
    @Autowired
    private IBamuSpReconciliationOrderService iBamuSpReconciliationOrderService;
    @Autowired
    private IBamuPurchaseApplyService ibamuPurchaseApplyService;
    @Override
    public YResult<PageResult<InvoiceVO>> pageList(InvoiceDto invoiceDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuInvoice> queryWrapper = new LambdaQueryWrapper<BamuInvoice>().
                like(StringUtils.isNotBlank(invoiceDto.getContractId()),BamuInvoice::getContractId,invoiceDto.getContractId())
                .like(StringUtils.isNotBlank(invoiceDto.getContractName()),BamuInvoice::getContractName,invoiceDto.getContractName())
                .eq(StringUtils.isNotBlank(invoiceDto.getProjectId()),BamuInvoice::getProjectId,invoiceDto.getProjectId())
                .like(StringUtils.isNotBlank(invoiceDto.getProjectName()),BamuInvoice::getProjectName,invoiceDto.getProjectName())
                .eq(StringUtils.isNotBlank(invoiceDto.getPurchaseDeptId()),BamuInvoice::getPurchaseDeptId,invoiceDto.getPurchaseDeptId())
                .like(StringUtils.isNotBlank(invoiceDto.getPurchaseDeptName()),BamuInvoice::getPurchaseDeptName,invoiceDto.getPurchaseDeptName())
                .eq(StringUtils.isNotBlank((CharSequence) invoiceDto.getInvoicingDate()),BamuInvoice::getInvoicingDate,invoiceDto.getInvoicingDate())
                .eq(StringUtils.isNotBlank((CharSequence) invoiceDto.getInvoicingPrice()),BamuInvoice::getInvoicingPrice,invoiceDto.getInvoicingPrice())
                .eq(StringUtils.isNotBlank(invoiceDto.getInvoicingStatus()),BamuInvoice::getInvoicingStatus,invoiceDto.getInvoicingStatus())
                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatus())
                .in(CollectionUtils.isNotEmpty(invoiceDto.getStatusList()), BamuInvoice::getStatus,invoiceDto.getStatusList())
//                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatusList())
                .eq(StringUtils.isNotBlank(invoiceDto.getContractMethod()), BamuInvoice::getContractMethod, invoiceDto.getContractMethod())
                .eq(BamuInvoice::getInvoiceDataType, 1)
                .eq(BamuInvoice::getIsDeleted, 0)
                .orderByDesc(BamuInvoice::getCreatedAt)
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()),
                        BamuInvoice::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()),
                BamuInvoice::getSupplierDeptId, BaseContext.getSupplierList());
//        LambdaQueryWrapper<BamuInvoiceSource> Wrapper = new LambdaQueryWrapper<BamuInvoiceSource>().
//                eq(BamuInvoiceSource::getInvoiceId,invoiceDto.getId());
//        BamuInvoiceSource bamuInvoiceSource = iBamuInvoiceSourceService.getOne(Wrapper);
        // 分页查询
        IPage<BamuInvoice> invoicePage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
        invoicePage = iBamuInvoiceService.page(invoicePage,queryWrapper);
        // 处理查询结果
        if(CollectionUtils.isEmpty(invoicePage.getRecords())){
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceVO> invoiceVOList = daoToVoList6(invoicePage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList,invoicePage.getCurrent(),invoicePage.getSize(),invoicePage.getPages(),invoicePage.getTotal()));
    }


    private BamuInvoiceSource getBamuInvoiceSource(String id) {
        LambdaQueryWrapper<BamuInvoiceSource> wrapper = new LambdaQueryWrapper<BamuInvoiceSource>()
                .eq(BamuInvoiceSource::getInvoiceId,id);
        return iBamuInvoiceSourceService.getOne(wrapper);
    }
    private List<InvoiceVO> daoToVoList6(List<BamuInvoice> records) {
        return records.stream().map(this::daoToVo6).collect(Collectors.toList());
    }

    private InvoiceVO daoToVo6(BamuInvoice bamuInvoice) {
        InvoiceVO invoiceVO = new InvoiceVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceVO);
//        BamuInvoiceSource source = getBamuInvoiceSource(bamuInvoice.getId());
//        if (source != null) {
//            invoiceVO.setOrderNum(getBamuInvoiceSource(bamuInvoice.getId()).getOrderNum());
//            invoiceVO.setOrderInvoiceNum(getBamuInvoiceSource(bamuInvoice.getId()).getOrderInvoiceNum());
//            int ordercanInvoiceNum =getBamuInvoiceSource(bamuInvoice.getId()).getOrderNum()-getBamuInvoiceSource(bamuInvoice.getId()).getOrderInvoiceNum();
//            invoiceVO.setOrdercanInvoiceNum(ordercanInvoiceNum);
//        }else {
//            invoiceVO.setOrderNum(0);
//            invoiceVO.setOrderInvoiceNum(0);
//            invoiceVO.setOrdercanInvoiceNum(0);
//        }
//        amuInvoiceSource bamuInvoiceSource = getBamuInvoiceSource(bamuInvoice.getId());

        return invoiceVO;
    }


    private List<InvoiceVO> daoToVoList(List<BamuInvoice> records) {
        return records.stream().map(this::daoToVo).collect(Collectors.toList());
    }

    private InvoiceVO daoToVo(BamuInvoice bamuInvoice) {
        InvoiceVO invoiceVO = new InvoiceVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceVO);
        return invoiceVO;
    }

    @Override
    public YResult<InvoiceinfoVO> getInvoiceById(Long id) {
        LambdaQueryWrapper<BamuInvoice> wrapper = new LambdaQueryWrapper<BamuInvoice>()
                .eq(BamuInvoice::getId, id);
        BamuInvoice bamuInvoice = iBamuInvoiceService.getOne(wrapper);
        // 处理查询结果
        if (Objects.isNull(bamuInvoice)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        return YResult.success(daoToInfoVO(bamuInvoice));
    }

    @Override
    public YResult<InvoiceInfosssVO> getInvoicessssById(Long id) {
        LambdaQueryWrapper<BamuInvoice> wrapper = new LambdaQueryWrapper<BamuInvoice>()
                .eq(BamuInvoice::getId, id);
        BamuInvoice bamuInvoice = iBamuInvoiceService.getOne(wrapper);
        // 处理查询结果
        if (Objects.isNull(bamuInvoice)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        return YResult.success(daoToInfoVO2(bamuInvoice));
    }
    private InvoiceInfosssVO daoToInfoVO2(BamuInvoice bamuInvoice) {
        InvoiceInfosssVO invoiceinfoVO = new InvoiceInfosssVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceinfoVO);
        return invoiceinfoVO;
    }

    private InvoiceinfoVO daoToInfoVO(BamuInvoice bamuInvoice) {
        InvoiceinfoVO invoiceinfoVO = new InvoiceinfoVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceinfoVO);
        return invoiceinfoVO;
    }
    @Override
    public YResult<String> saveInfo(InvoiceDto saveDto) {
        BamuInvoice bamuInvoice = new BamuInvoice();
        BeanUtils.copyProperties(saveDto,bamuInvoice);
        BamuPurchaseContract bamuPurchaseContract = iBamuPurchaseContractService.getById(saveDto.getContractId());
        bamuInvoice.setInvoiceDataType("1");
        bamuInvoice.setProjectName(bamuPurchaseContract.getProjectName());
        bamuInvoice.setContractNo(bamuPurchaseContract.getContractNo());
       // bamuInvoice.setInvoiceDataType("1");
        bamuInvoice.setInvoicingDate(ConvertUtil.getString2Date(saveDto.getInvoicingDate()));
        bamuInvoice.setInvoiceReceiveDate(ConvertUtil.getString2Date(saveDto.getInvoiceReceiveDate()));
        bamuInvoice.setInvoicingNo(saveDto.getInvoicingNo());
        bamuInvoice.setContractMethod(saveDto.getContractMethod());
        bamuInvoice.setSupplierDeptId(bamuPurchaseContract.getSupplierDeptId());
        bamuInvoice.setSupplierDeptName(bamuPurchaseContract.getSupplierDeptName());
        bamuInvoice.setProjectId(bamuPurchaseContract.getProjectId());
        bamuInvoice.setProjectName(bamuPurchaseContract.getProjectName());
        iBamuInvoiceService.saveOrUpdate(bamuInvoice);


        bamuInvoice.setInvoiceReceiveDate(ConvertUtil.getString2Date(saveDto.getInvoiceReceiveDate()));
        LambdaQueryWrapper<BamuPurchaseApply> wrapper2 = new LambdaQueryWrapper<BamuPurchaseApply>()
                .eq(BamuPurchaseApply::getContractId,bamuInvoice.getContractId());
        List<BamuPurchaseApply> bamuPurchaseApplylist = iBamuPurchaseApplyService.list(wrapper2);
        if (CollectionUtils.isNotEmpty(bamuPurchaseApplylist)) {
            for (BamuPurchaseApply b : bamuPurchaseApplylist) {
                BamuInvoiceApply bamuInvoiceApply = new BamuInvoiceApply();
                BeanUtils.copyProperties(bamuInvoice, bamuInvoiceApply);
                bamuInvoiceApply.setApplyId(b.getId());
                iBamuInvoiceApplyService.saveOrUpdate(bamuInvoiceApply);
                b.setSupplyInvoiceStatus("1");
                iBamuPurchaseApplyService.saveOrUpdate(b);
            }
        }
//        bamuInvoice.setReconciliationStartDate(saveDto.getReconciliationStartDate());
//        bamuInvoice.setReconciliationEndDate(saveDto.getReconciliationEndDate());
        if (CollectionUtils.isNotEmpty(saveDto.getReconciliationList())) {
            LambdaQueryWrapper<BamuSpReconciliationSettlement> projectWrapper = new LambdaQueryWrapper<BamuSpReconciliationSettlement>()
                    .in(BamuSpReconciliationSettlement::getId, saveDto.getReconciliationList());
            List<BamuSpReconciliationSettlement> bamuReconciliationSettlement = iBamuSpReconciliationSettlementService.list(projectWrapper);
            if(CollectionUtils.isNotEmpty(bamuReconciliationSettlement)) {
                for (int i = 0; i < bamuReconciliationSettlement.size(); i++) {
                    BamuSpReconciliationSettlement settlement = bamuReconciliationSettlement.get(i);
                    BamuInvoiceSource bamuInvoiceSource = new BamuInvoiceSource();
                    BeanUtils.copyProperties(bamuReconciliationSettlement.get(i), bamuInvoiceSource);
                    bamuInvoiceSource.setInvoiceId(bamuInvoice.getId());
                    bamuInvoiceSource.setBizId(bamuReconciliationSettlement.get(i).getId());
                    bamuInvoiceSource.setReconciliationCycle(ConvertUtil.getFormatDate(settlement.getReconciliationStartDate(),false,DateFormatPattern.MONTH_DAY_YEAR.getPattern())
                    +"至" + ConvertUtil.getFormatDate(settlement.getReconciliationEndDate(),false,DateFormatPattern.MONTH_DAY_YEAR.getPattern()));
                    bamuInvoiceSource.setSettlementTotalPrice(settlement.getReconciliationPrice());
                    iBamuInvoiceSourceService.saveOrUpdate(bamuInvoiceSource);
                }
            }
        }else if(CollectionUtils.isNotEmpty(saveDto.getPurchaseapplyIdList())){
            LambdaQueryWrapper<BamuPurchaseApply> projectWrapper1 = new LambdaQueryWrapper<BamuPurchaseApply>()
                    .in(BamuPurchaseApply::getId,saveDto.getPurchaseapplyIdList())
                    .eq(BamuPurchaseApply::getIsDeleted,0);
            List<BamuPurchaseApply> bamuPurchaseApply = iBamuPurchaseApplyService.list(projectWrapper1);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(bamuPurchaseApply)) {
                for (int i = 0; i < bamuPurchaseApply.size(); i++) {
                    LambdaQueryWrapper<BamuSpReconciliationSettlement> projectWrapper = new LambdaQueryWrapper<BamuSpReconciliationSettlement>()
                            .in(BamuSpReconciliationSettlement::getContractName, saveDto.getContractName());
                    List<BamuSpReconciliationSettlement> bamuReconciliationSettlement = iBamuSpReconciliationSettlementService.list(projectWrapper);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(bamuReconciliationSettlement)) {
                        for (int j = 0; j < bamuReconciliationSettlement.size(); j++) {
                            BamuSpReconciliationSettlement settlement = bamuReconciliationSettlement.get(j);
                            BamuInvoiceSource bamuInvoiceSource = new BamuInvoiceSource();
                            BeanUtils.copyProperties(bamuReconciliationSettlement.get(j), bamuInvoiceSource);
                            bamuInvoiceSource.setInvoiceId(bamuInvoice.getId());
                            bamuInvoiceSource.setBizId(bamuPurchaseApply.get(i).getId());
                            bamuInvoiceSource.setReconciliationCycle(ConvertUtil.getFormatDate(settlement.getReconciliationStartDate(),false,DateFormatPattern.MONTH_DAY_YEAR.getPattern())
                                    +"至" + ConvertUtil.getFormatDate(settlement.getReconciliationEndDate(),false,DateFormatPattern.MONTH_DAY_YEAR.getPattern()));
                            bamuInvoiceSource.setSettlementTotalPrice(settlement.getReconciliationPrice());
                            iBamuInvoiceSourceService.saveOrUpdate(bamuInvoiceSource);
                        }
                    }
                }
            }
        }
        iBamuInvoiceService.saveOrUpdate(bamuInvoice);
        return YResult.success(bamuInvoice.getId());
    }

    @Override
    public YResult<PageResult<InvoiceVO>> pageInvoiceList(InvoiceDto invoiceDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuInvoice> queryWrapper = new LambdaQueryWrapper<BamuInvoice>().
                eq(StringUtils.isNotBlank(invoiceDto.getContractId()),BamuInvoice::getContractId,invoiceDto.getContractId())
//                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceDataType()),BamuInvoice::getInvoiceDataType,invoiceDto.getInvoiceDataType())
                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceBindStatus()),BamuInvoice::getInvoiceBindStatus,invoiceDto.getInvoiceBindStatus())
                .eq(StringUtils.isNotBlank(invoiceDto.getInvoicingStatus()),BamuInvoice::getInvoicingStatus,invoiceDto.getInvoicingStatus())
                .between(StringUtils.isNotBlank(invoiceDto.getBeginDate()) && StringUtils.isNotBlank(invoiceDto.getEndDate()), BamuInvoice::getInvoicingDate,
                        ConvertUtil.getStartOfDay(ConvertUtil.getString2Date(invoiceDto.getBeginDate())),ConvertUtil.getEndOfDay(ConvertUtil.getString2Date(invoiceDto.getEndDate())))
                .eq(BamuInvoice::getInvoiceDataType, 1)
                .eq(BamuInvoice::getIsDeleted, 0);

//                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceDataType()),BamuInvoice::getInvoiceDataType,invoiceDto.getInvoiceDataType());
//                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatus());
        // 分页查询
        IPage<BamuInvoice> invoicePage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
        invoicePage = iBamuInvoiceService.page(invoicePage,queryWrapper);
        // 处理查询结果
        if(CollectionUtils.isEmpty(invoicePage.getRecords())){
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceVO> invoiceVOList = daoToVoList(invoicePage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList,invoicePage.getCurrent(),invoicePage.getSize(),invoicePage.getPages(),invoicePage.getTotal()));
    }

    @Override
    public YResult<PageResult<SpReconciliationOrderVO>> pageProjectList(InvoiceDto invoiceDto) {
        List<SpReconciliationOrderVO> allOrders = new ArrayList<>();
        LambdaQueryWrapper<BamuSpReconciliationSettlement> invoice = new LambdaQueryWrapper<BamuSpReconciliationSettlement>()
                .in(BamuSpReconciliationSettlement::getId, invoiceDto.getBizidList());
        List<BamuSpReconciliationSettlement> bamuSpReconciliationSettlementList = iBamuSpReconciliationSettlementService.list(invoice);
        if (CollectionUtils.isNotEmpty(bamuSpReconciliationSettlementList)) {
            for (BamuSpReconciliationSettlement settlement : bamuSpReconciliationSettlementList) {
                LambdaQueryWrapper<BamuSpReconciliation> projectWrapper = new LambdaQueryWrapper<>();
                projectWrapper.eq(BamuSpReconciliation::getContractId, settlement.getContractId());
                List<BamuSpReconciliation> bamuSpReconcilationList = iBamuSpReconciliationService.list(projectWrapper);
                if(CollectionUtils.isNotEmpty(bamuSpReconcilationList)) {
                    for (BamuSpReconciliation reconciliation : bamuSpReconcilationList) {
                        LambdaQueryWrapper<BamuSpReconciliationOrder> orderWrapper = new LambdaQueryWrapper<>();
                        orderWrapper.eq(BamuSpReconciliationOrder::getReconciliationId, reconciliation.getId());

                        IPage<BamuSpReconciliationOrder> settlementPage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
                        settlementPage = iBamuSpReconciliationOrderService.page(settlementPage, orderWrapper);

                        List<SpReconciliationOrderVO> voList = daoToVoList0(settlementPage.getRecords(),reconciliation);
                        allOrders.addAll(voList);

                        // 不再在这里返回结果，而是继续处理其他数据
                    }
                }
            }
        }


        // 检查是否查询到了数据
        if (allOrders.isEmpty()) {
            return YResult.success(new PageResult<>());
        }
        return YResult.success(new PageResult<>(allOrders, invoiceDto.getPageIndex(), invoiceDto.getPageSize(),
                (int) Math.ceil((double) allOrders.size() / invoiceDto.getPageSize()), allOrders.size()));

    }

    @Override
    public YResult<PageResult<SpReconciliationOrderVO>> pageProjectList2(InvoiceDto invoiceDto) {
        List<SpReconciliationOrderVO> allOrders = new ArrayList<>();
        LambdaQueryWrapper<BamuSupplyApply> invoice = new LambdaQueryWrapper<BamuSupplyApply>()
                .in(BamuSupplyApply::getId, invoiceDto.getBizidList());
        List<BamuSupplyApply> bamuReconciliationSettlementList = iBamuSupplyApplyService.list(invoice);
        if (CollectionUtils.isNotEmpty(bamuReconciliationSettlementList)) {
            for (BamuSupplyApply settlement : bamuReconciliationSettlementList) {
                LambdaQueryWrapper<BamuSpReconciliation> projectWrapper = new LambdaQueryWrapper<>();
                projectWrapper.eq(BamuSpReconciliation::getContractId, settlement.getContractId());
                List<BamuSpReconciliation> bamuReconcilationList = iBamuSpReconciliationService.list(projectWrapper);
                if (CollectionUtils.isNotEmpty(bamuReconcilationList)) {
                    for (BamuSpReconciliation reconciliation : bamuReconcilationList) {
                        LambdaQueryWrapper<BamuSpReconciliationOrder> orderWrapper = new LambdaQueryWrapper<>();
                        orderWrapper.eq(BamuSpReconciliationOrder::getReconciliationId, reconciliation.getId());

                        IPage<BamuSpReconciliationOrder> settlementPage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
                        settlementPage = iBamuSpReconciliationOrderService.page(settlementPage, orderWrapper);

                        List<SpReconciliationOrderVO> voList = daoToVoList8(settlementPage.getRecords(),reconciliation);
                        allOrders.addAll(voList);

                        // 不再在这里返回结果，而是继续处理其他数据
                    }
                }
            }

        }

        // 检查是否查询到了数据
        if (allOrders.isEmpty()) {
            return YResult.success(new PageResult<>());
        }
        return YResult.success(new PageResult<>(allOrders, invoiceDto.getPageIndex(), invoiceDto.getPageSize(),
                (int) Math.ceil((double) allOrders.size() / invoiceDto.getPageSize()), allOrders.size()));

    }

    @Override
    public YResult<InvoiceCountVO> getcount(Long id) {
        LambdaQueryWrapper<BamuInvoiceApply> invoiceWrapper = new LambdaQueryWrapper<BamuInvoiceApply>()
                .eq(BamuInvoiceApply::getInvoiceId, id);

        List<BamuInvoiceApply> bamuInvoiceApplyList = iBamuInvoiceApplyService.list(invoiceWrapper);
        BigDecimal totalTaxPrice = BigDecimal.ZERO;
        BigDecimal reconciliationPrice = BigDecimal.ZERO;
        if(CollectionUtils.isNotEmpty(bamuInvoiceApplyList)){
            for(int i= 0;i<bamuInvoiceApplyList.size();i++) {
                List<ReconciliationOrderVO> allOrders = new ArrayList<>();
                LambdaQueryWrapper<BamuSupplyApply> invoice = new LambdaQueryWrapper<BamuSupplyApply>()
                        .in(BamuSupplyApply::getId, bamuInvoiceApplyList.get(i).getApplyId());
                List<BamuSupplyApply> bamuReconciliationSettlementList = iBamuSupplyApplyService.list(invoice);
                if (CollectionUtils.isNotEmpty(bamuReconciliationSettlementList)) {
                    for (BamuSupplyApply settlement : bamuReconciliationSettlementList) {
                        LambdaQueryWrapper<BamuSpReconciliation> projectWrapper = new LambdaQueryWrapper<>();
                        projectWrapper.eq(BamuSpReconciliation::getContractId, settlement.getContractId());
                        List<BamuSpReconciliation> bamuReconcilationList = iBamuSpReconciliationService.list(projectWrapper);
                        if (CollectionUtils.isNotEmpty(bamuReconcilationList)) {
                            for (BamuSpReconciliation reconciliation : bamuReconcilationList) {
                                LambdaQueryWrapper<BamuSpReconciliationOrder> orderWrapper = new LambdaQueryWrapper<>();
                                orderWrapper.eq(BamuSpReconciliationOrder::getReconciliationId, reconciliation.getId());
                                BamuSpReconciliationOrder bamuReconciliationorder = iBamuSpReconciliationOrderService.getOne(orderWrapper);

                                if (bamuReconciliationorder != null) {
                                    totalTaxPrice = totalTaxPrice.add(bamuReconciliationorder.getTaxTotalPrice()); // 累加税总价
                                    reconciliationPrice = reconciliationPrice.add(bamuReconciliationorder.getReconciliationPrice()); // 累加总价
                                }
                                // 不再在这里返回结果，而是继续处理其他数据
                            }

                        }
                    }
                }
            }
        }
        InvoiceCountVO invoiceCountVO = new InvoiceCountVO();
        invoiceCountVO.setTaxTotalPrice(totalTaxPrice); // 累加税总价
        invoiceCountVO.setReconciliationPrice(reconciliationPrice); // 累加总价
        return YResult.success(invoiceCountVO);
    }

    private List<SpReconciliationOrderVO> daoToVoList8(List<BamuSpReconciliationOrder> bamuReconciliationOrderList, BamuSpReconciliation reconciliation) {
        return bamuReconciliationOrderList.stream()
                .map(order -> {
                    SpReconciliationOrderVO vo = new SpReconciliationOrderVO();
                    BeanUtils.copyProperties(order, vo);
                    enrichReconciliationOrderVO(vo, reconciliation); // 使用辅助方法设置额外字段
                    return vo;
                })
                .collect(Collectors.toList());
    }
    private void enrichReconciliationOrderVO(SpReconciliationOrderVO vo, BamuSpReconciliation reconciliation) {
        // 假设 BamuReconciliation 中有 getReconciliationStartDate() 方法
        if (reconciliation != null) {
            vo.setReconciliationStartDate(reconciliation.getReconciliationStartDate());
            vo.setReconciliationEndDate(reconciliation.getReconciliationEndDate());
        }
    }
    // 调整方法参数命名以更准确地反映其用途
    private List<SpReconciliationOrderVO> daoToVoList0(List<BamuSpReconciliationOrder> bamuSpReconciliationOrderList, BamuSpReconciliation reconciliation) {
        return bamuSpReconciliationOrderList.stream().map(order -> daoToVo0(order, reconciliation))
                .collect(Collectors.toList());
    }

    private SpReconciliationOrderVO daoToVo0(BamuSpReconciliationOrder bamuReconciliationOrder, BamuSpReconciliation reconciliation) {
        SpReconciliationOrderVO reconciliationOrderVO = new SpReconciliationOrderVO();
        BeanUtils.copyProperties(bamuReconciliationOrder, reconciliationOrderVO);
        reconciliationOrderVO.setReconciliationStartDate(reconciliation.getReconciliationStartDate());
        reconciliationOrderVO.setReconciliationEndDate(reconciliation.getReconciliationEndDate());
        return reconciliationOrderVO;
    }

    @Override
    public YResult<PageResult<InvoiceSourceOrderVO>> getInvoiceSourceOrderById(InvoiceSourceOrderDto invoiceSourceOrderDto) {
        LambdaQueryWrapper<BamuInvoiceSourceOrder> wrapper = new LambdaQueryWrapper<BamuInvoiceSourceOrder>()
                .eq(BamuInvoiceSourceOrder::getInvoiceId, invoiceSourceOrderDto.getInvoiceId());
//        BamuInvoiceSourceOrder bamuInvoice = iBamuInvoiceSourceOrderService.getOne(wrapper);

        // 分页查询
        IPage<BamuInvoiceSourceOrder> invoicePage = new Page<>(invoiceSourceOrderDto.getPageIndex(), invoiceSourceOrderDto.getPageSize());
        invoicePage = iBamuInvoiceSourceOrderService.page(invoicePage,wrapper);
        // 处理查询结果
        if(CollectionUtils.isEmpty(invoicePage.getRecords())){
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceSourceOrderVO> invoiceVOList = daoToVoList1(invoicePage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList,invoicePage.getCurrent(),invoicePage.getSize(),invoicePage.getPages(),invoicePage.getTotal()));
    }

    @Override
    public YResult<PageResult<InvoiceSourceOrderVO>> getInvoiceSourceOrderBycontractId(InvoiceSourceOrderDto invoiceSourceOrderDto) {
        LambdaQueryWrapper<BamuInvoiceSourceOrder> wrapper = new LambdaQueryWrapper<BamuInvoiceSourceOrder>()
                .in(BamuInvoiceSourceOrder::getBizId, invoiceSourceOrderDto.getIdList());
//        BamuInvoiceSourceOrder bamuInvoice = iBamuInvoiceSourceOrderService.getOne(wrapper);

        // 分页查询
        IPage<BamuInvoiceSourceOrder> invoicePage = new Page<>(invoiceSourceOrderDto.getPageIndex(), invoiceSourceOrderDto.getPageSize());
        invoicePage = iBamuInvoiceSourceOrderService.page(invoicePage,wrapper);
        // 处理查询结果
        if(CollectionUtils.isEmpty(invoicePage.getRecords())){
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceSourceOrderVO> invoiceVOList = daoToVoList1(invoicePage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList,invoicePage.getCurrent(),invoicePage.getSize(),invoicePage.getPages(),invoicePage.getTotal()));
    }

    @Override
    public YResult<PageResult<InvoiceSourceVO>> getInvoiceSourceById(InvoiceSourceDto invoiceSourceDto) {
        LambdaQueryWrapper<BamuInvoice> wrapper1 = new LambdaQueryWrapper<BamuInvoice>().eq(BamuInvoice::getId, invoiceSourceDto.getInvoiceId());
        BamuInvoice bamuInvoice = iBamuInvoiceService.getOne(wrapper1);
            LambdaQueryWrapper<BamuInvoiceSource> wrapper = new LambdaQueryWrapper<BamuInvoiceSource>()
                    .eq(BamuInvoiceSource::getInvoiceId, invoiceSourceDto.getInvoiceId());
//        BamuInvoiceSourceOrder bamuInvoice = iBamuInvoiceSourceOrderService.getOne(wrapper);

            // 分页查询
            IPage<BamuInvoiceSource> invoicePage = new Page<>(invoiceSourceDto.getPageIndex(), invoiceSourceDto.getPageSize());
            invoicePage = iBamuInvoiceSourceService.page(invoicePage,wrapper);
            // 处理查询结果
            if(CollectionUtils.isEmpty(invoicePage.getRecords())){
                return YResult.success(new PageResult<>());
            }
            // 转换为VO对象列表
            List<InvoiceSourceVO> invoiceVOList = daoToVoList2(invoicePage.getRecords());
            // 返回分页结果
            return YResult.success(new PageResult<>(invoiceVOList,invoicePage.getCurrent(),invoicePage.getSize(),invoicePage.getPages(),invoicePage.getTotal()));
    }

    @Override
    public YResult<PageResult<ProjectOrderVO>> getProjectOrderList(InvoiceSourceDto projectOrderDto) {
        LambdaQueryWrapper<BamuInvoice> wrapper = new LambdaQueryWrapper<BamuInvoice>()
                .eq(BamuInvoice::getId, projectOrderDto.getInvoiceId());
        BamuInvoice bamuInvoice = iBamuInvoiceService.getOne(wrapper);
        ProjectOrderDto projectOrderDto1 = new ProjectOrderDto();
        projectOrderDto1.setContractId(bamuInvoice.getContractId());
        // 分页查询
        IPage<BamuPurchaseApply> page = ibamuPurchaseApplyService.getPurchaseApplyList(projectOrderDto1);
        // 处理查询结果
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<ProjectOrderVO> voList = daoToVoList5(page.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, page.getCurrent(), page.getSize(),page.getPages(), page.getTotal()));
    }

    @Override
    public YResult<Boolean> deleteInfo(InvoiceDto reconciliationDto) {
        // 根据ID查询要删除的BamuPoSupply对象
        BamuInvoice bamuInvoice = iBamuInvoiceService.getById(Long.valueOf(reconciliationDto.getId()));

        // 如果对象不存在，返回错误信息
        if (bamuInvoice == null) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 调用Service层删除方法
        boolean removed = iBamuInvoiceService.removeById(Long.valueOf(reconciliationDto.getId()));

        // 返回删除结果
        if (removed) {
            return YResult.success(true);
        } else {
            return YResult.error(ResultMsgEnum.ERROR);
        }
    }

    private List<ProjectOrderVO> daoToVoList5(List<BamuPurchaseApply> daoList) {
        List<ProjectOrderVO> voList = new ArrayList<>(daoList.size());
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(daoList)) {
            return daoList.stream().map(this::dao2Vo).collect(Collectors.toList());
        }
        return voList;
    }

    /**
     * 转化并格式化
     * @param apply
     * @return ProjectOrderVO
     */
    private ProjectOrderVO dao2Vo(BamuPurchaseApply apply) {
        ProjectOrderVO vo = new ProjectOrderVO();
        try {
            BeanUtils.copyProperties(apply, vo);
            StringBuilder status = new StringBuilder();


            String orderStatus = "";
            if ((apply.getSupplyStatus()==null || apply.getSupplyStatus() == 0) && ConvertUtil.getIntValue(apply.getAuditStatus(),-1) != AuditStatusEnums.AUDIT_SUCCESS.getType()) {
                orderStatus = AuditStatusEnums.getDescriptionByType(ConvertUtil.getIntValue(apply.getAuditStatus()));
            }else {
                if (apply.getSupplyStatus() == SupplyStatus.SUPPLY_COMPLETION_ACCEPTANCE.getType()){
                    if (ConvertUtil.getIntValue(apply.getAuditStatus())==AuditStatusEnums.AUDIT_REJECT.getType() || ConvertUtil.getIntValue(apply.getAuditStatus())==AuditStatusEnums.AUDIT_REVOCATION.getType())
                        status.append(apply.getAuditStatus()).append("8");
                    orderStatus = OrderStatus.getDescriptionByType(status.toString());
                }else {
                    orderStatus = SupplyStatus.getDescriptionByType(apply.getSupplyStatus());
                }
            }
            vo.setOrderStatus(orderStatus);
            vo.setProjectInvoiceStatus(InvoiceStatusStatus.getDescriptionByType(apply.getProjectInvoiceStatus()));
            vo.setSupplyInvoiceStatus(InvoiceStatusStatus.getDescriptionByType(apply.getSupplyInvoiceStatus()));
            vo.setSettlementStatus(SettlementStatus.getDescriptionByType(apply.getSettlementStatus()));
            vo.setProjectReconciliationStatus(ReconciliationStatus.getDescriptionByType(apply.getProjectReconciliationStatus()));
            vo.setSupplierReconciliationStatus(ReconciliationStatus.getDescriptionByType(apply.getSupplierReconciliationStatus()));
//            vo.setCreatedAt(ConvertUtil.getFormatDate(apply.getCreatedAt(), false, "yyyy-MM-dd"));
            vo.setCopperDate(ConvertUtil.getFormatDate(apply.getCopperDate(), false, "yyyy-MM-dd"));
            vo.setReceivingTime(ConvertUtil.getFormatDate(apply.getReceivingTime(), false, "yyyy-MM-dd"));
            vo.setSupplyConfirmDate(ConvertUtil.getFormatDate(apply.getSupplyConfirmDate(), false, "yyyy-MM-dd"));
            vo.setTakeAt(ConvertUtil.getFormatDate(apply.getTakeAt(), false, "yyyy-MM-dd"));
            vo.setFlowSubmitDate(ConvertUtil.getFormatDate(apply.getFlowSubmitDate(), false, "yyyy-MM-dd"));
            vo.setBizId(apply.getId());
            String auditStatus = apply.getAuditStatus();
            String processInstanceId = apply.getProcessInstanceId();
            String modelSchemeInfoId = apply.getModelSchemeInfoId();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(auditStatus)
                    && org.apache.commons.lang3.StringUtils.equals(auditStatus, AuditStatusEnums.AUDIT.getType().toString())
                    && org.apache.commons.lang3.StringUtils.isNotBlank(modelSchemeInfoId)
                    && org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
                vo.setAuditButton(projectOrderAuditHandle.userIsAuditButton(modelSchemeInfoId, processInstanceId));
            }

        }catch (Exception e){
            log.error("ProjectOrderServiceImpl.daoToVo error", e);
        }
        return vo;
    }

    private List<InvoiceSourceVO> daoToVoList2(List<BamuInvoiceSource> records) {
        return records.stream().map(this::daoToVo2).collect(Collectors.toList());
    }

    private InvoiceSourceVO daoToVo2(BamuInvoiceSource bamuInvoice) {
        InvoiceSourceVO invoiceVO = new InvoiceSourceVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceVO);
        // 使用“至”作为分隔符拆分字符串
        String[] dates = invoiceVO.getReconciliationCycle().split("至");

        // 验证拆分结果是否包含两个日期
        if (dates.length == 2) {
            invoiceVO.setReconciliationStartDate(ConvertUtil.getString2Date(dates[0])); // 第一个日期
            invoiceVO.setReconciliationEndDate(ConvertUtil.getString2Date(dates[1])); // 第二个日期
        }
        invoiceVO.setYkorderInvoiceNum(getnum(bamuInvoice));
        return invoiceVO;
    }
    private Integer getnum(BamuInvoiceSource bamuInvoice){
        LambdaQueryWrapper<BamuInvoiceApply> wrapper = new LambdaQueryWrapper<BamuInvoiceApply>()
                .eq(BamuInvoiceApply::getInvoiceId, bamuInvoice.getInvoiceId());
        List<BamuInvoiceApply> bamuInvoiceApplyList = iBamuInvoiceApplyService.list(wrapper);
        int num = 0;
        for (BamuInvoiceApply bamuInvoiceApply : bamuInvoiceApplyList) {
            LambdaQueryWrapper<BamuSupplyApply> wrapper1 = new LambdaQueryWrapper<BamuSupplyApply>()
                    .eq(BamuSupplyApply::getId, bamuInvoiceApply.getApplyId());
            BamuSupplyApply bamuPurchaseApply = iBamuSupplyApplyService.getOne(wrapper1);

            if(bamuPurchaseApply.getProjectInvoiceStatus().equals("1")){
                num = num+1;
            }
        }
        return num;
    }
    private List<InvoiceSourceOrderVO> daoToVoList1(List<BamuInvoiceSourceOrder> records) {
        return records.stream().map(this::daoToVo1).collect(Collectors.toList());
    }

    private InvoiceSourceOrderVO daoToVo1(BamuInvoiceSourceOrder bamuInvoice) {
        InvoiceSourceOrderVO invoiceVO = new InvoiceSourceOrderVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceVO);
        return invoiceVO;
    }

    @Override
    public List<InvoiceExcelDto> export(InvoiceDto invoiceDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuInvoice> queryWrapper = new LambdaQueryWrapper<BamuInvoice>().
                like(StringUtils.isNotBlank(invoiceDto.getContractId()),BamuInvoice::getContractId,invoiceDto.getContractId())
                .like(StringUtils.isNotBlank(invoiceDto.getContractName()),BamuInvoice::getContractName,invoiceDto.getContractName())
                .eq(StringUtils.isNotBlank(invoiceDto.getProjectId()),BamuInvoice::getProjectId,invoiceDto.getProjectId())
                .like(StringUtils.isNotBlank(invoiceDto.getProjectName()),BamuInvoice::getProjectName,invoiceDto.getProjectName())
                .eq(StringUtils.isNotBlank(invoiceDto.getPurchaseDeptId()),BamuInvoice::getPurchaseDeptId,invoiceDto.getPurchaseDeptId())
                .like(StringUtils.isNotBlank(invoiceDto.getPurchaseDeptName()),BamuInvoice::getPurchaseDeptName,invoiceDto.getPurchaseDeptName())
                .eq(StringUtils.isNotBlank((CharSequence) invoiceDto.getInvoicingDate()),BamuInvoice::getInvoicingDate,invoiceDto.getInvoicingDate())
                .eq(StringUtils.isNotBlank((CharSequence) invoiceDto.getInvoicingPrice()),BamuInvoice::getInvoicingPrice,invoiceDto.getInvoicingPrice())
                .eq(StringUtils.isNotBlank(invoiceDto.getInvoicingStatus()),BamuInvoice::getInvoicingStatus,invoiceDto.getInvoicingStatus())
                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatus())
                .in(CollectionUtils.isNotEmpty(invoiceDto.getStatusList()), BamuInvoice::getStatus,invoiceDto.getStatusList())
//                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatusList())
                .eq(StringUtils.isNotBlank(invoiceDto.getContractMethod()), BamuInvoice::getContractMethod, invoiceDto.getContractMethod())
                .eq(BamuInvoice::getInvoiceDataType, 1)
                .eq(BamuInvoice::getIsDeleted, 0)
                .orderByDesc(BamuInvoice::getCreatedAt)
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()),
                        BamuInvoice::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()),
                        BamuInvoice::getSupplierDeptId, BaseContext.getSupplierList());
        List<BamuInvoice> contractMaterialList  = iBamuInvoiceService.list(queryWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contractMaterialList)){
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private InvoiceExcelDto convertToExcelDto(BamuInvoice bamuPurchaseApply){
        InvoiceExcelDto dto = new InvoiceExcelDto();
        BeanUtils.copyProperties(bamuPurchaseApply,dto);
        dto.setId(bamuPurchaseApply.getId());
        return dto;
    }
}
